package com.gpframework.module.wages.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gpframework.common.enums.YesNoEnum;
import com.gpframework.common.exception.CustomException;
import com.gpframework.common.utils.StringUtils;
import com.gpframework.module.wages.domain.GzMonthlySalesCommission;
import com.gpframework.module.wages.domain.GzPersonnelFoundation;
import com.gpframework.module.wages.domain.vo.GzMonthlySalesCommissionVo;
import com.gpframework.module.wages.mapper.GzMonthlySalesCommissionMapper;
import com.gpframework.module.wages.service.IGzMonthlySalesCommissionService;
import com.gpframework.module.wages.service.IGzPersonnelFoundationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
/**
 * @ClassName GzMonthlySalesCommission
 * @Author gpframework
 * @Date 2024-01-24
 * @Version 1.0.0
 * @Description 销售月度提成Service业务层处理
 */
@Service
public class GzMonthlySalesCommissionServiceImpl extends ServiceImpl<GzMonthlySalesCommissionMapper, GzMonthlySalesCommission> implements IGzMonthlySalesCommissionService {

    @Autowired
    private IGzPersonnelFoundationService iGzPersonnelFoundationService;
    @Autowired
    private IGzMonthlySalesCommissionService iGzMonthlySalesCommissionService;

    /**
     * @Description 查询列表返回VO 用于返回给前端的列表接口
     * @Author gpframework
     * @Date 2024-01-24
     * @Param [lqw]
     * @Return List<GzMonthlySalesCommissionVo>
     */
    @Override
    public List<GzMonthlySalesCommissionVo> listVo(QueryWrapper<GzMonthlySalesCommission> lqw) {
        return this.baseMapper.listVo(lqw);
    }


    @Override
    public List<GzMonthlySalesCommissionVo> listVoed(QueryWrapper<GzMonthlySalesCommission> lqw) {
        return this.baseMapper.listVoed(lqw);
    }

    /**
     * @Description 通过查询详情VO 用于返回给前端的列详情接口
     * @Author gpframework
     * @Date 2024-01-24
     * @Param [id]
     * @Return GzMonthlySalesCommissionVo
     */
    @Override
    public GzMonthlySalesCommissionVo getVoById(Long id) {
        return this.baseMapper.getVo(id);
    }

    @Override
    public void deleteByMonth(Date month) {
        this.baseMapper.delelteMonth(month);
    }

    @Override
    public String importListNote(List<GzMonthlySalesCommissionVo> excelList, boolean updateSupport) {
        if (StringUtils.isNull(excelList) || excelList.size() == 0) {
            throw new CustomException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (GzMonthlySalesCommissionVo gzMonthlySalesCommissionVo : excelList) {
            try {
                //查询数据
                GzMonthlySalesCommission monthlySalesCommission = iGzMonthlySalesCommissionService.getOne(new QueryWrapper<GzMonthlySalesCommission>()
                        .eq("name", gzMonthlySalesCommissionVo.getName())
                        .eq("department_name", gzMonthlySalesCommissionVo.getDepartmentName())
                        .eq("month", gzMonthlySalesCommissionVo.getMonth())
                        .eq("del_status", YesNoEnum.NO.getKey()));
                if (StringUtils.isNull(monthlySalesCommission)){
                    //新增销售月度提成
                    GzMonthlySalesCommission gzMonthlySalesCommission = Convert.convert(new TypeReference<GzMonthlySalesCommission>() {
                    }, gzMonthlySalesCommissionVo);

                    //复制userId
                    GzPersonnelFoundation gzPersonnelFoundation = iGzPersonnelFoundationService.getOne(new QueryWrapper<GzPersonnelFoundation>()
                            .eq("name", gzMonthlySalesCommissionVo.getName())
                            .eq("department_name", gzMonthlySalesCommissionVo.getDepartmentName())
                            .eq("del_status", YesNoEnum.NO.getKey()));

                    gzMonthlySalesCommission.setUserId(gzPersonnelFoundation.getId());

                    BigDecimal result = ((gzMonthlySalesCommission.getMonthlyTotalSales().subtract(gzMonthlySalesCommission.getStartingPointTaxation())).divide(BigDecimal.valueOf(100000))).add(BigDecimal.ONE);

                    gzMonthlySalesCommission.setSalesLevel(result);

                    successNum++;
                    successMsg.append("<br/>" + successNum + "、姓名 " + gzMonthlySalesCommission.getName() + " 导入成功");
                    iGzMonthlySalesCommissionService.save(gzMonthlySalesCommission);
                } else if (updateSupport) {
                    //更新销售月度提成
                    GzMonthlySalesCommission gzMonthlySalesCommission = Convert.convert(new TypeReference<GzMonthlySalesCommission>() {
                    }, gzMonthlySalesCommissionVo);

                    GzMonthlySalesCommission salesCommission = iGzMonthlySalesCommissionService.getOne(new QueryWrapper<GzMonthlySalesCommission>()
                            .eq("name", gzMonthlySalesCommissionVo.getName())
                            .eq("department_name", gzMonthlySalesCommissionVo.getDepartmentName())
                            .eq("month", gzMonthlySalesCommissionVo.getMonth())
                            .eq("del_status", YesNoEnum.NO.getKey()));
                    if (salesCommission!=null){
                        //获取ID
                        gzMonthlySalesCommission.setId(salesCommission.getId());
                    }

                    //复制userId
                    GzPersonnelFoundation gzPersonnelFoundation = iGzPersonnelFoundationService.getOne(new QueryWrapper<GzPersonnelFoundation>()
                            .eq("name", gzMonthlySalesCommissionVo.getName())
                            .eq("department_name", gzMonthlySalesCommissionVo.getDepartmentName())
                            .eq("del_status", YesNoEnum.NO.getKey()));
                    gzMonthlySalesCommission.setUserId(gzPersonnelFoundation.getId());

                    BigDecimal result = ((gzMonthlySalesCommission.getMonthlyTotalSales().subtract(gzMonthlySalesCommission.getStartingPointTaxation())).divide(BigDecimal.valueOf(100000))).add(BigDecimal.ONE);

                    gzMonthlySalesCommission.setSalesLevel(result);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、姓名 " + gzMonthlySalesCommission.getName() + " 更新成功");
                    iGzMonthlySalesCommissionService.updateById(gzMonthlySalesCommission);
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、姓名 " + gzMonthlySalesCommissionVo.getName() + " 已存在");
                }

            }catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、姓名 " + gzMonthlySalesCommissionVo.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }

        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

}
